﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace Lacrima.Framework.Infrastructure
{
    /// <summary>
    /// 二进制序列化和反序列化
    /// </summary>
    public static class BinarySerializer
    {
        public static void Serialize<T>(T obj, string filePath)
        {
            BinaryFormatter transfer = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            transfer.Serialize(ms, obj);

            byte[] b = new byte[ms.Length];
            b = ms.GetBuffer();

            FileStream fs = File.Create(filePath);
            fs.Write(b, 0, b.Length);

            ms.Close();
            fs.Close();
        }

        public static T Deserialize<T>(string filePath)
        {
            FileStream fs = File.OpenRead(filePath);
            byte[] b = new byte[fs.Length];
            fs.Read(b, 0, b.Length);
            fs.Close();

            BinaryFormatter transfer = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(b);
            T t = (T)transfer.Deserialize(ms);
            ms.Close();
            return t;
        }
    }
}
